package com.sinodata.bsm.cicp.collector.sqlserver;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class TabCollector extends AbstractJDBCCollector {

    private static final Logger logger = Logger.getLogger(TabCollector.class);

    //    private static final int DEADLOCK_WAIT_TIME = 60;

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        try {
            String[] propMetas = getPropMeta();
            //        String serverName = this.getParamMap().get("服务器名");
            //        String databaseName = this.getParamMap().get("数据库名");
            //        String owner = this.getParamMap().get("所有者");
            //        String tableName = this.getParamMap().get("表名");
            String serverName = this.getParamMap().get("ServerName");
            String databaseName = this.getParamMap().get("DBName");
            String owner = this.getParamMap().get("Owner");
            String tableName = this.getParamMap().get("TableName");

            String sql = "execute " + databaseName + ".dbo.sp_spaceused '" + owner + "." + tableName + "'";
            String[] rs = TabCollectorStr(serverName, sql, ip, databaseName);
            //由于通过sql查询出的结果中包含单位"KB"，这在后面解析会报错，所以在这里去掉单位
            String[] newRs = cutUtil(rs);
            ResPropertyValue propertyValueX = new ResPropertyValue();
            ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
            for (int i = 0; i < propMetas.length; i++) {
                propValues[i] = ResPropertyValue.createPropValue(newRs[i], propMetas[i]);
            }
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
        } catch (Exception ex) {
            logger.error("failed to collect sqlserver tabcollector", ex);
            throw new CollectorException(ex);
        }
        return values;
    }

    private String[] cutUtil(String[] rs) {
        Pattern pattern = Pattern.compile("^(\\d+).*$");
        Matcher matcher = null;
        for (int i = 0; i < rs.length; i++) {
            matcher = pattern.matcher(rs[i]);
            if (matcher.find()) {
                rs[i] = matcher.group(1);
            }
        }
        return rs;
    }

    private String[] TabCollectorStr(String serverName, String sql, String ip, String databaseName) throws CollectorException {
        String[] sb = new String[5];

        try {
            ResultSet rs = this.getCachedResultSet("sqlserver", ip, serverName, sql);
            while (rs.next()) {
                String rowCount = rs.getString(2);
                sb[0] = rowCount == null ? "" : rowCount.trim();
                String reservedSize = rs.getString(3);
                sb[1] = reservedSize == null ? "" : reservedSize.trim();
                String dataSize = rs.getString(4);
                sb[2] = dataSize == null ? "" : dataSize.trim();
                String indexSize = rs.getString(5);
                sb[3] = indexSize == null ? "" : indexSize.trim();
                String unusedSize = rs.getString(6);
                sb[4] = unusedSize == null ? "" : unusedSize.trim();
            }
        } catch (Exception ex) {
            logger.error("while connect database : ", ex);
            throw new CollectorException(ex);
        }

        return sb;
    }

    @Override
    public String[] getParamMeta() {
        //        return new String[] { "服务器名", "数据库名", "所有者", "表名" };
        return new String[] { "ServerName", "DBName", "Owner", "TableName" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "DataRows", "TotalReservedSpaceSize", "DataUsedSpaceSize", "IndexUsedSpaceSize", "UnusedSpaceSize" };
    }
}
